<?php

namespace App\Http\Controllers\Seller;

use App\Models\User;
use App\Repositories\Seller\UserTransactionRepository;
use Illuminate\Http\Request;

class UserTransactionController extends BaseController
{
    //
    public function __construct()
    {
        $this->repo = new UserTransactionRepository();
    }

    public function fetchList(Request $request){
        $where['seller_id'] = $this->id();
        $user_id = $request->get('user_id',-1);
        if($user_id>-1){
            $where['user_id'] = $user_id;
        }
        $param = $request->all();
        $param['with'] = ['user'];
        $page = $this->repo->pagination($where,$param);
        return $this->success($page);
    }

    /**
     * 充值
     * @param Request $request
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function topUp(Request $request, User $user){
        if($user->seller_id!=$this->id()){
            return $this->error('用户不存在',[],404,404);
        }
        $money = $request->get('money',0);
        if($money<=0){
            return $this->error('充值金额不能小于0');
        }
        if($money+$user->balance>9999999.99){
            return $this->error('金额溢出');
        }
        $money = (float)$money;
        $price = $request->get('price',0);
        $price = (float)$price;
        if($price<0){
            return $this->error('实收金额不能小于0');

        }
        $desc = $request->get('desc','充值');
        return $this->repo->topUp($user,$money,$price,$desc)?$this->success([],'充值成功'):$this->error('充值失败');
    }

    /**
     * 扣费
     * @param Request $request
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function consume(Request $request, User $user){
        if($user->seller_id!=$this->id()){
            return $this->error('用户不存在',[],404,404);
        }
        $money = $request->get('money',0);
        if($money<=0){
            return $this->error('消费金额不能小于0');
        }
        if($user->balance-$money<0){
            return $this->error('余额不足');
        }
        $money = (float)$money;
        $desc = $request->get('desc','消费');
        return $this->repo->consume($user,$money,$desc)?$this->success([],'扣费成功'):$this->error('扣费失败');
    }

}
